<?php
// +----------------------------------------------------------------------
// | Cron控制器
// +----------------------------------------------------------------------
// | Since: 2014-09-15 16:02
// +----------------------------------------------------------------------
// | Author: shioujun <shioujun@gmail.com>
// +----------------------------------------------------------------------
namespace Crontab\Controller;

use Think\Controller;
use Common\Model\OpenIdModel as OpenId;
use Common\Model\UserModel as User;
use Com\Weixin\WeixinApi;

/**
 */
class TaskController extends Controller
{
    
    /**
     * 更新access token
     */
    function gettoken()
    {
        $wx_obj = new WeixinApi();
        
        $access_token = $wx_obj->getToken( true );
        
        echo $access_token."\n\r";
        var_dump( S('access_token') );
        die;
        
        
        return false;
    }    
    
    /**
     * 更新用户信息
     */
    public function updateWeixinUserInfo()
    {
        $u = new User();
        $userInfo = $u->where(" `nickname` is null or logo is null ")
        ->limit(100)
        ->select();
        $c = 0;
        foreach ($userInfo as $key => $value) {
            if ($c > 10) {
                $c = 0;
                sleep(1);
            }
            $c ++;
            $openid_obj = new OpenId();
            $openid_info = $openid_obj->uid2OpenidInfo($value['id']);
            if( $openid_info && $openid_info['state']==1 ){
                $this->getBasicinfo( $openid_info['openid']  );
            }else{
                echo "Uid:{$value['id']} 的openid没有找到或者state=0\n";
            }
        }
    }
    
    
    private function getBasicinfo($openid)
    {
        $user_obj = new User();
        $info = $user_obj->getWeixinUserDetailInfo($openid);
        
        if( $info ){
            $where = array();
            $where['openid'] = $openid;
            
            $update = $info;
            $rs = $user_obj->where($where)->save($update);
            if( !$rs ){
                echo "更新失败\n\n";
            }
        }else{
            echo "未获得 openid : {$openid} 的信息";
        }
    }
    
}